package com.sdy.usercenter.web.controller.api;

import com.sdy.auth.api.AuthApi;
import com.sdy.auth.api.model.UserInfo;
import com.sdy.auth.client.service.SsoService;
import com.sdy.common.model.BizException;
import com.sdy.common.model.Response;
import com.sdy.common.model.Result;
import com.sdy.common.utils.Assert;
import com.sdy.mvc.controller.BaseController;
import com.sdy.mvc.utils.HttpUtil;
import com.sdy.redis.service.RedisService;
import com.sdy.usercenter.biz.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/auth")
public class AuthApiController extends BaseController {
    @Autowired
    private RedisService redisService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SsoService ssoService;
    @Autowired
    private AuthApi authApi;

    private static final int TOKEN_EXPIRE_SECOND = 60 * 10;

    /**
     * 登录
     * key = sha256(sha256(password) + sha256(appkey) + timestamp) # lowercase
     */
    @PostMapping("/login")
    public Response login(HttpServletRequest request) throws BizException {
        String username = request.getParameter("username");
        String appid = request.getParameter("appid");
        String key = request.getParameter("key");
        // 时间戳 单位ms
        String timestamp = request.getParameter("timestamp");
        Assert.isBlank(username, "username不为空");
        Assert.isBlank(appid, "appid不为空");
        Assert.isBlank(key, "key不为空");
        Assert.isBlank(timestamp, "timestamp不为空");
        Result<UserInfo> result = authApi.loginS(username, appid, key, timestamp, HttpUtil.getIpAddr(request)).getData();
        if (!result.getSuccess()) {
            return Response.error(result.getMessage(), result.getCode());
        }
        String token = UUID.randomUUID().toString();
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("id", result.getData().getUserId());
        userInfo.put("username", result.getData().getUserName());
        userInfo.put("appid", appid);
        userInfo.put("token", token);
        redisService.set(token, result.getData(), TOKEN_EXPIRE_SECOND);
        return Response.success(userInfo);
    }

    /**
     * 获取下属用户集合
     */
    @GetMapping("/manage/subuser")
    public Response subuser(HttpServletRequest request) {
        UserInfo userInfo = ssoService.getUserInfo(request);
        return authApi.subuser(userInfo.getUserId());
    }
}
